package com.yike.user.lkl.incoming;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
@Slf4j
public class RsaDecrypt {
    private static final String  pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCp5aV3ZiXG2R8Yd8Nxocv+cF7VAUHBc0TF4MNne7mI8wM2yEP2QgI+rK1qDf6G7ZFPhutpIHKQchpolbSuC0vgaHpSjO9OUs1fpnK/JjZq9o8DatUsA0n4Fccec9NBbV5dy5yrwro7xmDpsevp1/IeiIssi1+iD+nBWqqVFx7GVQIDAQAB";
    public static void main(String[] args) throws Exception {
        String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCp5aV3ZiXG2R8Yd8Nxocv+cF7VAUHBc0TF4MNne7mI8wM2yEP2QgI+rK1qDf6G7ZFPhutpIHKQchpolbSuC0vgaHpSjO9OUs1fpnK/JjZq9o8DatUsA0n4Fccec9NBbV5dy5yrwro7xmDpsevp1/IeiIssi1+iD+nBWqqVFx7GVQIDAQAB";
        String data = "rX9Q928mtz5mAeMh9OiRCAFeXSQNgyrkRjmzXlnJ6rPvANuZO6MBn1xQHNT4/gH1C45V6LMc/GFwugJYXTptZNSzmK0LMS9XlF3hFI8eEQ15NKF9WexZBjr1TfkvqIsHKs207MhWUdpQbeMBlxbaFn1x1XJDEyZVKe0v2uMXNf4cMqk+1opKhBfnbaKhoQjNSEr0WZM8+DEeFaJH6Iki38ccWXyd01fQ2BdQuTzjNA09yqupCzWt3CR8BcVPcuw+SFTP9nxfjTA4DH9DNT1gXX/0bbRI7JFMBqRs5wfBqfIxsPFGNMSvv8nT1dH0ZPk/O31sRBoMfauR9DZ1arzprRf5cKUr8fvZV0w6AXevyX5Bh/QJZtsXw0bEV7zPPJcUbNXxqPYw0Ok13344qAZjJQb2nUvrkDGJ2ofLJPkbLiQfNTYYdAKdmmUNKUTC58RUPi8HmyBV/1D95YaXfBHMooImZOno6XyshG/005qcrDOezsfHNW//AgADmWGL/yWu";
        //String decrypt = RsaDecrypt.decrypt(pubKey, data);
        //System.out.println("解密结果：" + decrypt);
    }

    public static <T> T decrypt(String data, Class<T> clazz) throws Exception {
        String decrypt = decrypt(pubKey, data);
        log.info("拉卡拉推送信息-解密结果：{}", decrypt);
        return JSON.parseObject(decrypt, clazz);
    }
    /**
     * 公钥解密
     * @param pubKey Base64公钥
     * @param data Base64数据
     * @return 解密字符串
     * @throws Exception 解密异常
     */
    public static String decrypt(String pubKey, String data) throws Exception {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] keyBytes = decoder.decode(pubKey.getBytes());
        byte[] dataBytes = decoder.decode(data.getBytes());
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(keyBytes)));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] cache;
        for (int i = 0, offset = 0, length = dataBytes.length; length - offset > 0; i++, offset = i * 128) {
            if (length - offset > 128) {
                cache = cipher.doFinal(dataBytes, offset, 128);
            } else {
                cache = cipher.doFinal(dataBytes, offset, length - offset);
            }
            out.write(cache, 0, cache.length);
        }
        return out.toString();
    }

}
